package hello.word.m2.maven.config;

import hello.word.m2.maven.dao.BookDao;
import hello.word.m2.maven.jpa.JpalPlugin;
import hello.word.m2.maven.jpa.Jpqls;
import hello.word.m2.maven.support.AutoSqlObject;
import io.micronaut.context.BeanContext;
import io.micronaut.context.annotation.Factory;
import io.micronaut.core.reflect.ClassUtils;
import io.opentracing.Tracer;
import io.opentracing.contrib.jdbi3.OpentracingJdbi3Plugin;
import io.opentracing.util.GlobalTracer;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.core.statement.SqlStatements;
import org.jdbi.v3.jodatime2.JodaTimePlugin;
import org.jdbi.v3.jpa.JpaPlugin;
import org.jdbi.v3.sqlobject.SqlObjectPlugin;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.sql.DataSource;

@Factory
public class DataSourceConfig {

   /* Tracer tracer;

    @Inject
    public DataSourceConfig(Tracer tracer) {
        this.tracer = tracer;
    }*/

  /*  private final DataSource dataSource;

    public DataSourceConfig(DataSource dataSource) {
        this.dataSource = dataSource;
    }*/

    @Singleton
    Jdbi getJdbi(DataSource dataSource){
        System.out.println("_______++++++++______");
        Jdbi jdbi = Jdbi.create(new TransactionAwareDataSourceProxy(dataSource));
        jdbi.installPlugin(new JpaPlugin());
        jdbi.installPlugin(new JodaTimePlugin());
        jdbi.installPlugin(new SqlObjectPlugin());
        jdbi.installPlugin(new JpalPlugin());

//        AutoSqlObject autoSqlObject = new AutoSqlObject();
        Object object= jdbi.onDemand(BookDao.class);
//        autoSqlObject.setObjectMap(BookDao.class.getName(), object);
        jdbi.configure(AutoSqlObject.class, a -> a.setObjectMap(BookDao.class.getName(), object));
//        jdbi.configure(Jpqls.class, j -> j.setJpqlBuilder(jpqls));
        /*GlobalTracer.registerIfAbsent(tracer);
        jdbi.installPlugin(new OpentracingJdbi3Plugin());*/


        SqlStatements sqlStatementsConfig = jdbi.getConfig(SqlStatements.class);
        sqlStatementsConfig.setUnusedBindingAllowed(true);
        return jdbi;
    }

    void testSqlObjec(Jdbi jdbi){
        Class clazz = ClassUtils.forName("hello.word.m2.maven.dao.BookDao",Thread.currentThread().getContextClassLoader()).get();
        BeanContext.build().createBean(jdbi.onDemand(clazz).getClass());
    }
}
